﻿using MongoDB.Bson;
using MongoDBSample.Common.Utils;
using MongoDBSample.DataAccess;
using MongoDBSample.Models.DB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MongoDBSample.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private DataManager _dataManager;

        public HomeController()
        {
            _dataManager = new DataManager();
        }

        public ActionResult Index()
        {
            IList<Attachment> attachments = _dataManager.GetAllttachments();
            return View(attachments);
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                MongoHelper<Attachment> attachments = new MongoHelper<Attachment>();
                string fileName = System.IO.Path.GetFileName(file.FileName); // Just get the file name. Example: c:\users\priya\test.jpg => test.jpg
                ObjectId fileId = attachments.AddFile(file.InputStream, fileName); // Save the file data into Mango GridFS


                Attachment attachment = new Attachment() { Name = fileName, Owner = User.Identity.Name, FileId = fileId };
                _dataManager.AddAttachment(attachment);
                return RedirectToAction("Index");
            }

            return View();
        }

        [HttpGet]
        public ActionResult Delete(string id)
        {
            Attachment attachment = _dataManager.GetAttachment(new ObjectId(id));
            if (!attachment.Owner.Equals(User.Identity.Name))
            {
                throw new UnauthorizedAccessException("You do not have access to delete this object");
            }
            return View(attachment);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult ConfirmDelete(string id, string fileId)
        {
            // delete file
            MongoHelper<Attachment> attachments = new MongoHelper<Attachment>();
            attachments.DeleteFile(new ObjectId(fileId));

            _dataManager.DeleteAttachment(new ObjectId(id));
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Views a jar file
        /// </summary>
        /// <param name="id">File Id</param>
        /// <returns></returns>
        public ActionResult ViewJarFile(string id)
        {
            // TODO : Hardcoded class name = Main..!!!!
            string result =
                string.Format(@"<Applet Code='Main' Archive='{0}' width=800 Height=600></Applet>", Url.Action("GetFile", new { id = id }));
            return new ContentResult()
            {
                Content = result,
                ContentType = "text/html",
            };
        }

        /// <summary>
        /// Views a video file
        /// </summary>
        /// <param name="id">File Id</param>
        /// <returns></returns>viewjar
        public ActionResult ViewVideo(string id)
        {
            string result =
                string.Format(@"<video width='320' height='240' controls><source src='{0}' type='video/mp4'></video>", Url.Action("GetFile", new { id = id, mimeType = "video/mp4" }));
            return new ContentResult()
            {
                Content = result,
                ContentType = "text/html",
            };
        }

        public FileResult GetFile(string id)
        {
            var fileId = new ObjectId(id);
            MongoHelper<Attachment> attachments = new MongoHelper<Attachment>();
            return File(attachments.GetFile(fileId), "application/x-java-applet"); // application/x-java-applet or application/java-archive
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        /// <summary>
        /// Reads the content of an uploaded file.
        /// </summary>
        /// <param name="file">File to be read</param>
        /// <returns>File content</returns>
        private byte[] ReadFileContent(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                byte[] binaryData = new byte[file.ContentLength];
                file.InputStream.Read(binaryData, 0, file.ContentLength);
                return binaryData;
            }

            return null;
        }
    }
}
